/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.layouts.BoxLayout;
import core.DistrictsManager;
import core.DriverManager;
import datamodel.District;
import datamodel.DriverState;
import network.Connection;
import network.packets.DriversQueueResponce;
import network.packets.Packet;
import view.additional.TimerLabel;
import view.commands.CenterCommand;
import view.commands.ConnectCommand;
import view.commands.ExitCommand;
import view.commands.FunctionsCommand;
import view.commands.SettingsCommand;

/**
 *
 * @author Kvest
 */
public class MainForm extends Form implements DriverManager.DriverStateChangedListener, DriverManager.TimerAction 
{
    private ExitCommand exitCommand;
    private ConnectCommand connectCommand;
    private SettingsCommand settingsCommand;
    private FunctionsCommand functionsCommand;
    private CenterCommand centerCommand;
    private CenterCommand centerCommandNoConnection;
    
    private TextArea order;
    private Label driverState;
    private Label district;
    private Label driversOrder;
    private Label noConnectionLabelPart1;
    private Label noConnectionLabelPart2;
    private TimerLabel timerLabel;
    
    private Label inBlackListLabel;
    private Label noConnectionLabel;
    private boolean showNoConnection;
    
    public MainForm()
    {
        super("");

        showNoConnection = false;
        
        exitCommand = new ExitCommand();
        centerCommandNoConnection = new CenterCommand(exitCommand);
        connectCommand = new ConnectCommand();
        settingsCommand = new SettingsCommand();
        functionsCommand = new FunctionsCommand();
        centerCommand = new CenterCommand(functionsCommand);
        
        init();

        DriverManager.getManager().setDriverCurrentStateChangedListener(this);
        DriverManager.getManager().setTimerActionListener(this);
        
        //Подписываемся на событие обновления списка позывных на стоянке
        Connection.getConnection().setPacketListener(Packet.DRIVERS_QUEUE_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                DriversQueueResponce responce = (DriversQueueResponce)packet;
                setDriversOrder(responce.getDriversQueue());
            }
        });
    }
    
    private void init()
    {  
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setCyclicFocus(false);
        
        //Заявка      
        order = new TextArea("", 1, 30);
        order.setEditable(false);
       // order.setFocusable(false);
        order.setGrowByContent(true);
        
        //Состояние водителя
        driverState = new Label("");
        driverState.setAlignment(Label.CENTER);
        driverState.setFocusable(true);
        
        //Таймер
        timerLabel = new TimerLabel();
        
        //Район
        district = new Label("");
        district.setAlignment(Label.CENTER);
        district.setFocusable(true);

        driversOrder = new Label("");
        driversOrder.setFocusable(true);
        driversOrder.setEndsWith3Points(false);
        driversOrder.setTickerEnabled(true);

        //Метка на случай если нет соединения
        noConnectionLabelPart1 = new Label("no_connection1"); 
        noConnectionLabelPart1.setAlignment(Label.CENTER);
        noConnectionLabelPart2 = new Label("no_connection2"); 
        noConnectionLabelPart2.setAlignment(Label.CENTER);
        
        inBlackListLabel = new Label("in_blacklist");
        inBlackListLabel.setAlignment(Label.CENTER);
        inBlackListLabel.getStyle().setBgColor(0xff0000, true);
        
        noConnectionLabel = new Label("no_connection");
        noConnectionLabel.setAlignment(Label.CENTER);
        noConnectionLabel.getStyle().setBgColor(0xff0000, true); 
    }
    
    public void update(boolean needRepaint)
    {
        //Устанавливаем данные
        setContent();
        
        //Устанавливаем команды
        setCommands();

        if (needRepaint)
        {
            repaint();
        }
    }
    
    public void show()
    {
        update(false);
        
        super.show();
    }
    
    private void setContent()
    {    
        boolean addTimerLabel = contains(timerLabel);
        
        //Чистим форму
        removeAll();
        
        if (Connection.getConnection().isConnected() || showNoConnection)
        {
            showNoConnection = true;
            if (!Connection.getConnection().isConnected())
            {
                addComponent(noConnectionLabel);
            }
            else if (DriverManager.getManager().isInBlackList())
            {
                addComponent(inBlackListLabel);
            }
            
            DriverManager manager = DriverManager.getManager();
            if (manager.getCurrentOrderID() != DriverManager.UNKNOWN_VALUE)
            {
                order.setText(manager.getCurrentOrderText());
            }
            else
            {
                order.setText((new Label("no_order")).getText());
            }
            addComponent(new Label("order"));
            addComponent(order);
            
            driverState.setText(manager.getCurrenntState().getName());
            addComponent(new Label("state"));
            addComponent(driverState);
            
            if (addTimerLabel)
            {
                addComponent(timerLabel);
            }
            
            District districtValue = DistrictsManager.getDistrictsManager().getDistrictById(manager.getDistrictID()); 
            if (districtValue != null)
            {
                district.setText(districtValue.getName());
            }
            else
            {
                if (manager.getDistrictID() == DriverManager.UNKNOWN_VALUE)
                {
                    district.setText("not_registered");
                }
                else
                {
                    district.setText("unknown_district");
                    district.setText(district.getText() + " (id=" + Integer.toString(manager.getDistrictID()) + ")");
                }
            }
            addComponent(new Label("district"));
            addComponent(district);

            //Список позывных
            addComponent(driversOrder);
        }
        else
        {
            addComponent(noConnectionLabelPart1);
            addComponent(noConnectionLabelPart2);
        }
    }
    
    private void setCommands()
    {
        //Удаляем команды
        removeAllCommands();
        
        if (Connection.getConnection().isConnected())
        {
            if (!Display.getInstance().isTouchScreenDevice())
            {
                addCommand(centerCommand);
            }
            addCommand(functionsCommand);
        }
        else
        {
            
            if (!Display.getInstance().isTouchScreenDevice())
            {
                addCommand(centerCommandNoConnection);
            }            
            addCommand(exitCommand);
            addCommand(settingsCommand);
            addCommand(connectCommand);
        }
    }
    
    public void driverStateChanged(DriverState oldState, DriverState newState)
    {
        driverState.setText(newState.getName());
        repaint();
    }

    public void setDriversOrder(String driversOrder)
    {
        this.driversOrder.setText(driversOrder);
        repaint();
    }

    public void showTimer() 
    {
        if (!contains(timerLabel))
        {
            int index = getComponentIndex(driverState);
            if (index != -1)
            {
                addComponent(index + 1, timerLabel);
            }
        }
        repaint();
    }

    public void hideTimer() 
    {
        removeComponent(timerLabel);
        repaint();
    }

    public void timerValueChanged(int milliseconds) 
    {
        timerLabel.setTime(milliseconds);
        repaint();
    }
}
